def bubbleSort(alist):
    '''
    冒泡排序: 比较相邻两个元素的大小,进行交换, 每一趟比较后, 就有一个最大的元素沉入底部
    >>> bubbleSort([9,1,7,3,2,11,33,0])
    [0, 1, 2, 3, 7, 9, 11, 33]
    '''
    length = len(alist)
    for i in range(length):
        for j in range(length-1-i):
            if alist[j] > alist[j+1]:
                temp = alist[j]
                alist[j] = alist[j+1]
                alist[j+1] = temp
    return alist

# print(bubbleSort([9,1,7,3,2,11,33,0]))


def modifiedBubbleSort(alist):
    '''
    改进过的冒泡排序: 当已经有序后, 就提前结束循环
    >>> modifiedBubbleSort([9,1,7,3,2,11,33,0])
    [0, 1, 2, 3, 7, 9, 11, 33]
    '''
    length = len(alist)
    i = 0
    exchange = True
    while i < length and exchange:
        for j in range(length-1-i):
            if alist[j] > alist[j+1]:
                exchange = True
                temp = alist[j]
                alist[j] = alist[j+1]
                alist[j+1] = temp
        i += 1
    return alist
# print(modifiedBubbleSort([9,1,7,3,2,11,33,0]))

if __name__ == '__main__':
    import doctest
    doctest.testmod(verbose=True)
